<template>
  <div class="avatar">
    <comhead></comhead>
    <img v-lazy="userInfo.img" alt="">
    <input @change="change" ref="file" type="file" accept="image/jpg,image/jpeg,image/png">
    <img width="100" :src="url" alt="">
    <button @click="submit">修改</button>
  </div>
</template>
<script>
import comhead from '@/components/header'
import {updateAvatar} from '@/api/api'
import { mapGetters } from 'vuex'
import COS from 'cos-js-sdk-v5'
var Bucket = '1-1256914858'
var Region = 'ap-chengdu'
// const Bucket = 'tage-1258294351'
// const Region = 'ap-shanghai'
var cos = new COS({
  getAuthorization: function (options, callback) {
    var authorization = COS.getAuthorization({
      SecretId: 'AKIDnOlsjKaohKkwta6JK7ew1sTpysWuGvZw',
      SecretKey: 'IMAi0iDTVIvJSMzNWP2QYQ2OV7XjiT1K',
      // SecretId: 'AKIDEKGbr2yvcDD4rU7Maij3DD6qPpV3tHcp',
      // SecretKey: 'DID1eBmR2Tq382oQxMboz76gDrTzNjy2',
      Method: options.Method,
      Key: options.Key,
      Query: options.Query,
      Headers: options.Headers,
      Expires: 60
    })
    callback(authorization)
  }
})
export default {
  data () {
    return {
      img: localStorage.getItem('img'),
      file: '',
      url: ''
    }
  },
  components: {
    comhead
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    change () {
      let that = this
      let file = this.$refs.file.files[0]
      var reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function (e) {
        that.url = e.target.result
        // that.img = localStorage.getItem('img')
        // console.log(this)
      }
    },
    submit () {
      const that = this
      const file = this.$refs.file.files[0]
      console.log(this.$refs.file.files[0])
      if (!file) return
      cos.putObject({
        Bucket: Bucket,
        Region: Region,
        Key: 'avatar/' + parseInt(Math.random() * 100000) + file.name,
        Body: file,
        onProgress: function (progressData, callback) {
        }
      }, function (err, data) {
        console.log(err, data)
        updateAvatar({account: localStorage.getItem('account'), img: 'http://' + data.Location}).then(res => {
          that.$message.success(res.msg)
          that.$router.push('list')
        })
      })
    }
    // submit () {
    //   var form = new FormData()
    //   console.log(this.$refs.file.files[0])
    //   form.append('tou', this.$refs.file.files[0])
    //   form.append('account', localStorage.getItem('account'))
    //   localStorage.setItem('img', localStorage.getItem('account'))
    //   updateAvatar(form).then(res => {
    //     this.$message.success(res.msg)
    //     this.$router.push('list')
    //   })
    // }
  }
}
</script>
<style lang="less" scoped>
.avatar{
  width: 100px;
}
</style>
